#include "VIN_EventSystem.h"

void VIN_EventSystem::ResgisterClient(EVENTID eventID,IListener* client)
{
	if(client || AlreadyRegistered(eventID, client) )
		mClientDataBase.insert( make_pair( eventID, client) );
}

void VIN_EventSystem::UnregisterClient(EVENTID eventID, IListener *client)
{
	pair<multimap<EVENTID, IListener*>::iterator,
		multimap<EVENTID, IListener*>::iterator> range;

	range = mClientDataBase.equal_range(eventID);

	for( multimap<EVENTID, IListener*>::iterator mmIter = range.first;
		mmIter != range.second; mmIter++)
	{
		if((*mmIter).second == client)
		{
			mmIter = mClientDataBase.erase(mmIter);
			break;
		}
	}
}

void VIN_EventSystem::DispatchEvent(CEvent *pEvent)
{
	pair<multimap<EVENTID, IListener*>::iterator,
		multimap<EVENTID, IListener*>::iterator> range;

	range = mClientDataBase.equal_range(pEvent->GetEventID());

	for(multimap<EVENTID, IListener*>::iterator mmIter = range.first;
		mmIter != range.second; mmIter++)
	{
		(*mmIter).second->HandleEvent(pEvent);
	}
}

bool VIN_EventSystem::AlreadyRegistered(EVENTID eventID, IListener *client)
{
	bool IsAlreadyResgistered = false;

	pair<multimap<EVENTID, IListener*>::iterator,
		multimap<EVENTID, IListener*>::iterator> range;

	range = mClientDataBase.equal_range(eventID);

	for( multimap<EVENTID, IListener*>::iterator mmIter = range.first;
		mmIter != range.second; mmIter++)
	{
		if((*mmIter).second == client)
		{
			IsAlreadyResgistered = true;
			break;
		}
	}
	return IsAlreadyResgistered;
}

void VIN_EventSystem::SendEvent(EVENTID eventID, void *Data)
{
	CEvent newEvent(eventID, Data);

	mCurrentEvents.push_back(newEvent);
}

void VIN_EventSystem::ProcessEvents()
{
	while(mCurrentEvents.size())
	{
		DispatchEvent(&mCurrentEvents.front());
		mCurrentEvents.pop_front();
	}
}

void VIN_EventSystem::ClearEvents()
{
	mCurrentEvents.clear();
}

void VIN_EventSystem::ShutdownEventSystem()
{
	mCurrentEvents.clear();
}

VIN_EventSystem* VIN_EventSystem::GetInstance()
{
	static VIN_EventSystem instance;
	return &instance;
}